package com.dake.jdk8.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

@Component
public class PropertyUtils {

    private static final String PROPERTIES_NAME = "ruleId.properties";

    private static Properties properties = new Properties();

    public static void main(String[] args) {
        String polno = getProperty("POLNO");
        System.out.println(polno);

        String polno1 = getPropertyByApi("POLNO");
        System.out.println(polno1);
    }

    public static String getPropertyByApi(String propertyKey) {
        Properties properties = null;
        try {
            properties = PropertiesLoaderUtils.loadProperties(
                new InputStreamResource(PropertyUtils.class.getClassLoader().getResourceAsStream(PROPERTIES_NAME)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(propertyKey, "123456");
    }

    public static String getProperty(String propertyKey){
        if (properties.size() == 0) {
            InputStream resourceAsStream = PropertyUtils.class.getClassLoader().getResourceAsStream(PROPERTIES_NAME);
            try {
                properties.load(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return properties.getProperty(propertyKey);
        } else {
            return StringUtils.EMPTY;
        }
    }
}
